<template>
  <el-table
    :data="model.tableData"
    border
    :header-cell-style="{
      background: '#eef1f6',
      color: '#606266'
    }"
  >
    <template #empty>
      <el-empty :image-size="40" description="暂无数据"></el-empty>
    </template>
    <el-table-column type="index" label="序号" />
    <el-table-column prop="target" label="目标及考核指标"></el-table-column>
    <el-table-column label="类型">
      <template #default="{ row }">
        {{
          row.resultType &&
          model.types.find(el => el.key === row.resultType).label
        }}
      </template>
    </el-table-column>
    <el-table-column prop="num" label="数值"></el-table-column>

    <el-table-column prop="finishStatus" label="是否完成">
      <template #default="{ row }">
        {{ row.finishStatus === "0" ? "是" : "否" }}
      </template>
    </el-table-column>
    <el-table-column prop="finishTime" label="完成时间"></el-table-column>
    <el-table-column prop="finishDesc" label="完成情况"></el-table-column>
    <el-table-column label="操作" width="220" fixed="right">
      <template #default="{ row, $index }">
        <el-button v-if="isEdit" type="text" @click="edit(row, $index)"
          >编辑</el-button
        >
        <el-button v-else type="text" @click="edit(row, $index)"
          >查看</el-button
        >
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
    title="目标及考核指标"
    v-model="model.dialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <el-form
      :model="model.formData"
      @submit.prevent
      ref="dialogFormRef"
      :rules="dialogFormRules"
      label-width="150px"
      :disabled="!isEdit"
    >
      <el-row>
        <el-col>
          <el-form-item label="目标及考核指标">
            {{ model.formData.target }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="类型">
            {{
              model.formData.resultType &&
              model.types.find(el => el.key === model.formData.resultType).label
            }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="数值">
            {{ model.formData.num }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="是否完成" prop="finishStatus">
            <el-select
              style="width: 100%"
              v-model="model.formData.finishStatus"
              clearable
              placeholder="请选择"
              value-key="id"
            >
              <el-option
                v-for="item in model.dones"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item> </el-col
      ></el-row>

      <el-row>
        <el-col>
          <el-form-item label="完成时间" prop="finishTime">
            <el-date-picker
              style="width: 100%"
              v-model="model.formData.finishTime"
              value-format="YYYY-MM-DD hh:mm:ss"
              type="date"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="完成情况" prop="finishDesc">
            <el-input type="textarea" v-model="model.formData.finishDesc" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="科研成果">
            <el-select
              v-model="model.scientifics"
              clearable
              filterable
              multiple
              placeholder="请输入科研名称"
              @change="handlePublicscientific"
              :remote-method="getScientific"
              style="width: 100%"
              remote
            >
              <el-option
                v-for="item in model.scientificList"
                :key="item.id"
                :label="item.kyName"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-table
              v-if="model.scientificTableList.length > 0"
              :data="model.scientificTableList"
              border
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            >
              <el-table-column type="index" label="序号" />
              <el-table-column prop="kyNum" label="编号"> </el-table-column>
              <el-table-column prop="kyName" label="成果名称">
              </el-table-column>

              <el-table-column label="成果来源">
                <template #default="{ row }">
                  {{ row.kyTypeName || "其他" }}
                </template>
              </el-table-column>
              <el-table-column label="附件">
                <template #default="{ row }">
                  <el-link
                    v-for="(item, index) in row.kyAttachmentArr"
                    :key="index"
                    @click="handlePreview(item)"
                    >{{ item.fileName }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column fixed="right" label="操作" width="80">
                <template #default="{ row }">
                  <el-button type="text" size="small" @click="jump(row)"
                    >查看详情</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- <el-input type="textarea" v-model="model.formData.finishDesc" /> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="附件">
            <ecm-upload
              :files="model.defaultFileList"
              :docid="model.docid"
              @setFile="handlelSuccess2"
            >
            </ecm-upload>
            <!-- <el-upload
              name="uploadFile"
              multiple
              :accept="acceptTypes"
              :action="uploadComUrl"
              :headers="uploadHeaders"
              :on-success="handlelSuccess2"
              :on-remove="handlelRemove2"
              :on-error="handleError"
              :file-list="model.defaultFileList"
              :before-upload="beforeAvatarUpload"
              :on-preview="handlePreview"
            >
              <el-button size="small" type="primary" v-if="isEdit"
                >点击上传</el-button
              >
              <template #tip v-if="isEdit">
                <div class="el-upload__tip">
                  支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件,文件大小不得大于10M。
                </div>
              </template>
            </el-upload> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row justify="end" v-if="isEdit">
      <el-button @click="model.dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleDialogSubmit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script lang="ts" setup>
import { cloneDeep } from "lodash-es";
import { ref, watch, reactive } from "vue";
import { postScientificList } from "/@/api/scientific";
import EcmUpload from "/@/components/ecmUpload/index.vue";
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  isEdit: {
    type: Boolean,
    default: false
  }
});
const dialogFormRef = ref<HTMLFormElement | null>(null) as any;
const dialogFormRules = ref({
  finishStatus: [
    { required: true, message: "请选择完成类型", trigger: "change" }
  ],
  finishTime: [
    { required: true, message: "请选择完成时间", trigger: "change" }
  ],
  finishDesc: [{ required: true, message: "请输入完成情况", trigger: "change" }]
});

const model: any = reactive({
  docid: window["ecmDocType"].project,
  scientificList: [],
  scientifics: [],
  scientificTableList: [],
  defaultFileList: [],
  index: -1,
  formData: {
    type: "",
    num: "",
    target: "",
    finishStatus: "",
    finishTime: "",
    finishDesc: "",
    attachmentList: [],
    resultType: ""
  },
  tableData: [],
  dialogFormVisible: false,
  dones: [
    { key: "0", label: "是" },
    { key: "1", label: "否" }
  ],
  types: [
    { key: "1", label: "新产品" },
    { key: "2", label: "新装置" },
    { key: "3", label: "新材料" },
    { key: "4", label: "新工艺/方法/模式" },
    { key: "5", label: "专利" },
    { key: "6", label: "软件著作权" },
    { key: "7", label: "论文" },
    { key: "8", label: "专著" },
    { key: "9", label: "标准" },
    { key: "10", label: "研究报告" },
    { key: "11", label: "计算机软件" },
    { key: "12", label: "技术指标" },
    { key: "13", label: "其他" }
  ]
});
const handlePreview = (item: any) => {
  if (item.response) {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item?.response.data.uuidFile}&fileName=${item?.response.data.fileName}`
    );
  } else {
    window.open(
      `${location.origin}${location.pathname}#/online?uuidFile=${item.uuidFile}&fileName=${item.fileName}`
    );
  }
};
const jump = item => {
  const local = location.href.split("#")[0];
  let path = "";
  switch (item.kyTypeName) {
    case "专利":
      path = "#/document/scientific/patent";
      break;
    case "软件著作":
      path = "#/document/scientific/software";
      break;
    case "论文":
      path = "#/document/scientific/paper";
      break;
    case "专著":
      path = "#/document/scientific/book";
      break;
    case "标准":
      path = "#/document/scientific/standard";
      break;
    case "科技奖励":
      path = "#/document/scientific/award";
      break;
    case "科技制度建设":
      path = "#/document/scientific/building";
      break;
    default:
      path = "#/document/scientific/other";
      window.open(
        `${local}${path}?id=${item.id}&projectNum=${item.projectManageCode}&mode='look'`
      );
      return;
  }

  window.open(
    `${local}${path}?id=${item.kyId}&projectNum=${item.projectManageCode}&mode='look'`
  );
};
const getScientific = async (query = "") => {
  const { code, data } = await postScientificList({
    scientificScouce: "1",
    ...{ kyName: query },
    ...{
      pageNum: 1,
      pageSize: 0
    }
  });
  if (code === 200) {
    model.scientificList = data.list;
    // model.tableData = data.list;
    // model.total = data.rows;
  }
};

const handlelSuccess2 = res => {
  model.defaultFileList = res.file;
  model.formData.attachmentList = res.file;
  // if (res.code === 200) {
  //   nextTick(() => {
  //     model.defaultFileList = fileList;
  //     if (!model.formData.attachmentList) {
  //       model.formData.attachmentList = [];
  //     }
  //     model.formData.attachmentList.push(res.data);
  //     model.formData.attachmentList.map(el => {
  //       el["name"] = el.fileName;
  //     });
  //   });
  // }
};

const handleDialogSubmit = async () => {
  const isValid = await new Promise(resolve =>
    dialogFormRef.value.validate(resolve)
  );
  if (isValid) {
    model.tableData[model.index] = model.formData;
    model.tableData[model.index]["scientificAchv"] = model.scientifics;
    model.tableData[model.index]["scientificAchvs"] = model.scientificTableList;
    model.dialogFormVisible = false;
  }
};

const handlePublicscientific = item => {
  model.scientificTableList = [];
  item.forEach((el: any) => {
    const target: any = model.scientificList.find(obj => obj.id === el);
    target.kyAttachmentArr =
      target.kyAttachmentArr == null ? [] : target.kyAttachmentArr;
    // if (target.kyAttachmentArr) {
    target.kyAttachmentArr.map(el => {
      el["name"] = el.fileName;
    });
    // }

    model.scientificTableList.push(target);
  });
};
const edit = (row, index) => {
  model.scientifics = row.scientificAchv || [];
  model.scientificTableList = row.scientificAchvs || [];
  model.index = index;
  model.dialogFormVisible = true;
  model.formData = cloneDeep(row);
  if (model.formData.attachmentList) {
    model.formData.attachmentList.map((el: any) => {
      el["name"] = el.fileName;
    });

    model.defaultFileList = model.formData.attachmentList;
  } else {
    model.formData.attachmentList = [];
    model.defaultFileList = [];
  }
  // console.log(row);
};
getScientific();
watch(
  () => props.data,
  (newVal: any) => {
    if (newVal && newVal.length) {
      model.tableData = newVal;
    }
  },
  { immediate: true }
);
</script>
<style lang="scss" scoped>
.title {
  margin: 0;
  margin-bottom: 20px;
}
</style>
